/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/7/6 14:43
 */
package com.gitee.mechanic.shiro.filter;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Set;

/**
 * 自定义 roles or 的 filter
 * 由于Shiro没有提供roles or的filter，因此自己写一个。
 *
 * @author mechanic
 * @version 0.0.1
 */
public class RolesOrAuthorizationFilter extends AuthorizationFilter {

    public final static String NAME = "roles_or";

    @Override
    protected boolean isAccessAllowed(
      ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;

        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }

        for (String roles : rolesArray) {
            if (subject.hasRole(roles)) {
                return true;
            }
        }

        Set<String> roles = CollectionUtils.asSet(rolesArray);
        return subject.hasAllRoles(roles);
    }
}
